package com.siecomzg.transport.handler;

import android.os.Bundle;

import com.siecomzg.constconfig.ConstDefine;
import com.siecomzg.proto.Message;
import com.siecomzg.transport.CallbackMap;
import com.siecomzg.transport.CallbackTask;
import com.siecomzg.transport.CommonClient;
import com.siecomzg.transport.DeviceCallback;
import com.siecomzg.transport.SiecomDevice;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created on 2017/2/13.
 */

public class UpdateHandler extends CommonHandler {

    public static boolean upDateFail = false;
    @Override
    public void onReceive(CommonClient server, Message.siecomproto msg) {
        String msgid = msg.getMsgid();
        HashMap<String, CallbackTask> callbackTaskHashMap = CallbackMap.getCallbackTaskHashMap();
        if (callbackTaskHashMap.containsKey(msgid)) {
            CallbackTask callbackTask = callbackTaskHashMap.get(msgid);
            DeviceCallback callback = callbackTask.getCallback();
            callbackTask.getTimer().cancel();
            boolean isOnMain = callbackTask.isOnMain();
            int respondCmd = msg.getCmd();
            if (respondCmd == ConstDefine.UPDATE_FW_RESPOND) {
                updateResond(msg, callback, isOnMain);
            }

        }
    }

    private void updateResond(Message.siecomproto msg, DeviceCallback callback, boolean isOnMain) {
        int errno = msg.getError();
        if (errno == 0) {
            upDateFail = false;
            try {
                JSONObject jsonObject = new JSONObject(msg.getRespond());
                if (jsonObject.getInt("flag") == 2) {
                    Bundle bundle = new Bundle();
                    SiecomDevice.deliverResult(callback, SiecomDevice.Result.START, bundle, isOnMain);
                }
                if (jsonObject.getInt("flag") == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("data", jsonObject.getInt("data"));
                    SiecomDevice.deliverResult(callback, SiecomDevice.Result.SUCCEED, bundle, isOnMain);
                }
                if (jsonObject.getInt("flag") == 0) {
                    Bundle bundle = new Bundle();
                    SiecomDevice.deliverResult(callback, SiecomDevice.Result.COMPLETED, bundle, isOnMain);
                    CallbackMap.getCallbackTaskHashMap().remove(msg.getMsgid());
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else {
            upDateFail = true;
            Bundle bundle = new Bundle();
            bundle.putInt("code", errno);
            bundle.putString("message", msg.getRespond());
            SiecomDevice.deliverResult(callback, SiecomDevice.Result.ERROR, bundle, isOnMain);

        }

    }
}
